package com.carpedil.movie;

import com.carpedil.client.service.FeiginClientService;
import com.carpedil.common.dto.OrderDTO;
import com.carpedil.movie.service.MovieService;
import com.carpedil.util.StringUtil;
import com.rabbitmq.client.Channel;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.messaging.handler.annotation.Header;

import java.io.IOException;

/** @author Administrator */
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@EnableFeignClients(
    basePackages = {"com.carpedil.client.service", "com.carpedil.client.order.service"})
@MapperScan("com.carpedil.movie.mapper")
@EnableDiscoveryClient
public class MovieSysMain {
  public static void main(String[] args) {
    SpringApplication.run(MovieSysMain.class, args);
  }

  @Autowired MovieService movieService;
  @Autowired FeiginClientService clientService;

  @RabbitListener(queues = "OrderQueue")
  public void getOrderInfo(
      OrderDTO orderDTO, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag) {
    // 库存-1
    boolean flag =
        movieService.updateStorageByProcedure(orderDTO.getMovieName(), orderDTO.getOrderId());
    if (flag) {
      // 更新订单状态(订单系统和客户端系统)
      flag = movieService.updateOrderStatus(orderDTO.getOrderId(), StringUtil.BOOKING_COMPLETED);
      // 将订单放入内存
      StringUtil.list.add(orderDTO);
    }
    try {
      if (flag) {
        // 手动确认  tag--队列的标记 ，false-->不批量处理
        channel.basicAck(tag, false);
        // 不手动确认
        // channel.basicNack(tag, false, true);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  @RabbitListener(queues = "deadQueue")
  public void getOrderInfoFromDeadQueue(
      OrderDTO orderDTO, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag) {
    // 库存-1
    boolean flag = movieService.updateStorage(orderDTO.getMovieName());
    if (flag) {
      // 更新订单状态(订单系统和客户端系统)
      flag = movieService.updateOrderStatus(orderDTO.getOrderId(), StringUtil.BOOKING_COMPLETED);
    }
    try {
      if (!flag) {
        // 手动确认  tag--队列的标记 ，false-->不批量处理
        channel.basicAck(tag, false);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
